﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.IO;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Collections;
using System.Web.Script.Serialization;

namespace PollServer
{
    public class Common
    {
        /// <summary>  
        /// 时间戳转为C#格式时间  
        /// </summary>  
        /// <param name=”timeStamp”></param>  
        /// <returns></returns>  
        static public DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow);
        }

        /// <summary>  
        /// DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name=”time”></param>  
        /// <returns></returns>  
        static public int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        /// <summary>  
        /// 3次encode_base64编码 
        /// </summary>  
        /// <param name=”time”></param>  
        /// <returns></returns>  
        static public string Encode_Base64(string src)
        {
            src = Convert.ToBase64String(Encoding.UTF8.GetBytes(src));
            src = Convert.ToBase64String(Encoding.UTF8.GetBytes(src));
            src = Convert.ToBase64String(Encoding.UTF8.GetBytes(src));


            return src;
        }
    }

    public class MySQLDBConnetion : IDisposable
    {
        private MySqlConnection connection = null;
        public string dbname = "";

        public MySQLDBConnetion(bool mode, string serverip, string catalog)
        {
            //if (mode)
            //    Connetion("dbwrit", "writ$#@", serverip, catalog);
            //else
            //    Connetion("dbread", "read@#$", serverip, catalog);
            if (mode)
                Connetion("datawrit", "asdfREWQ!@#$writ601", serverip, catalog, "3306");
            else
                Connetion("dbread", "read@#$", serverip, catalog, "3306");

            dbname = catalog;
        }
        public MySQLDBConnetion(string serverip, string account, string password, string catalog, string port)
        {
            dbname = catalog;
            Connetion(account, password, serverip, catalog, port);
        }

        public void Dispose()
        {
            connection.Close();
            connection.Dispose();
        }

        public void Connetion(string user, string password, string serverip, string dbname, string port)
        {
            if (connection != null)
                connection.Close();

            string connStr = "Server=" + serverip + ";Database=" + dbname + ";Uid= " + user + ";" + "Pwd=" + password + ";Port=" + port + ";Character Set=utf8";
            connection = new MySqlConnection(connStr);
            connection.Open();
        }

        public int NonQueryExec(string sqlcmd)
        {
            if (connection == null)
                return 0;

            MySqlCommand setcode = new MySqlCommand(sqlcmd, connection);
            setcode.CommandType = CommandType.Text;
            int result = setcode.ExecuteNonQuery();
            return result;
        }

        public DataTable GetDataTable(string sqlcmd)
        {
            if (connection == null)
                return null;

            MySqlCommand setcode = new MySqlCommand(sqlcmd, connection);
            setcode.CommandType = CommandType.Text;

            MySqlDataAdapter da = new MySqlDataAdapter(setcode);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
    }

    public class INI
    {
        // 声明INI文件的写操作函数 WritePrivateProfileString()
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        // 声明INI文件的读操作函数 GetPrivateProfileString()
        [System.Runtime.InteropServices.DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

        private string sPath = null;
        public INI(string path)
        {
            this.sPath = path;
        }
        public void WriteValue(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
            // section=配置节，key=键名，path=路径
            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            return temp.ToString();
        }
    }

    public class HttpWebResponseUtility
    {
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "text/html";
            //request.UserAgent = DefaultUserAgent;
            //if (!string.IsNullOrEmpty(userAgent))
            //{
            //    request.UserAgent = userAgent;
            //}
            if (timeout.HasValue)
            {
                request.Timeout = timeout.Value;
            }
            
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }

            return response;
        }
        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        /// <param name="url">请求的URL</param>  
        /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
        /// <param name="timeout">请求的超时时间</param>  
        /// <param name="userAgent">请求的客户端浏览器信息，可以为空</param>  
        /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
        /// <param name="cookies">随同HTTP请求发送的Cookie信息，如果不需要身份验证可以为空</param>  
        /// <returns></returns>  
        //public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
        //{
        //    if (string.IsNullOrEmpty(url))
        //    {
        //        throw new ArgumentNullException("url");
        //    }
        //    if (requestEncoding == null)
        //    {
        //        throw new ArgumentNullException("requestEncoding");
        //    }
        //    HttpWebRequest request = null;
        //    //如果是发送HTTPS请求  
        //    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        //    {
        //        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        //        request = WebRequest.Create(url) as HttpWebRequest;
        //        request.ProtocolVersion = HttpVersion.Version10;
        //    }
        //    else
        //    {
        //        request = WebRequest.Create(url) as HttpWebRequest;
        //    }
        //    request.Method = "POST";
        //    request.ContentType = "application/x-www-form-urlencoded";

        //    if (!string.IsNullOrEmpty(userAgent))
        //    {
        //        request.UserAgent = userAgent;
        //    }
        //    else
        //    {
        //        request.UserAgent = DefaultUserAgent;
        //    }

        //    if (timeout.HasValue)
        //    {
        //        request.Timeout = timeout.Value;
        //    }
        //    if (cookies != null)
        //    {
        //        request.CookieContainer = new CookieContainer();
        //        request.CookieContainer.Add(cookies);
        //    }
        //    //如果需要POST数据  
        //    if (!(parameters == null || parameters.Count == 0))
        //    {
        //        StringBuilder buffer = new StringBuilder();
        //        int i = 0;
        //        foreach (string key in parameters.Keys)
        //        {
        //            if (i > 0)
        //            {
        //                buffer.AppendFormat("&{0}={1}", key, parameters[key]);
        //            }
        //            else
        //            {
        //                buffer.AppendFormat("{0}={1}", key, parameters[key]);
        //            }
        //            i++;
        //        }
        //        byte[] data = requestEncoding.GetBytes(buffer.ToString());
        //        using (Stream stream = request.GetRequestStream())
        //        {
        //            stream.Write(data, 0, data.Length);
        //        }
        //    }
        //    return request.GetResponse() as HttpWebResponse;
        //}
    }

    //多元
    public class Multimap<U, T> : SortedList
    {
        public Multimap()
        {
        }

        public /*override */ object this[U key]
        {
            get
            {
                if (this.IndexOfKey(key) >= 0)
                {
                    List<T> o = (List<T>)base[key];
                    return o;
                }
                return null;
            }

            set
            {
                if (this.IndexOfKey(key) >= 0)
                {
                    List<T> o = (List<T>)this[key];
                    o.Add((T)value);
                    return;
                }
                List<T> ol = new List<T>();
                ol.Add((T)value);
                base[key] = ol;
            }
        }
    }
    
    //datatable 帮助类
    public class TableHelper
    {
            #region Json字符串转换为DataTable 实例方法
            public DataTable JsonToDataTable(string json)
            {
        		DataTable  dt= ToDataTable(json);
                return dt;
            }
            #endregion

            #region DataTable 转换为Json 字符串
            /// <summary>
            /// DataTable 对象 转换为Json 字符串
            /// </summary>
            /// <param name="dt"></param>
            /// <returns></returns>
            public static string ToJson(DataTable dt)
            {
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                ArrayList arrayList = new ArrayList();
                foreach (DataRow dataRow in dt.Rows)
                {
                    Dictionary<string, object> dictionary = new Dictionary<string, object>(); //实例化一个参数集合
                    foreach (DataColumn dataColumn in dt.Columns)
                    {
                        dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToString());
                    }
                    arrayList.Add(dictionary); //ArrayList集合中添加键值
                }

                return javaScriptSerializer.Serialize(arrayList);  //返回一个json字符串
            }
            #endregion

            #region Json 字符串 转换为 DataTable数据集合
            /// <summary>
            /// Json 字符串 转换为 DataTable数据集合
            /// </summary>
            /// <param name="json"></param>
            /// <returns></returns>
            public static DataTable ToDataTable(string json)
            {
                DataTable dataTable = new DataTable();  //实例化
                DataTable result;
                try
                {
                    JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                    javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
                    ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
                    if (arrayList.Count > 0)
                    {
                        foreach (Dictionary<string, object> dictionary in arrayList)
                        {
                            if (dictionary.Keys.Count<string>() == 0)
                            {
                                result = dataTable;
                                return result;
                            }
                            if (dataTable.Columns.Count == 0)
                            {
                                foreach (string current in dictionary.Keys)
                                {
                                    dataTable.Columns.Add(current, dictionary[current].GetType());
                                }
                            }
                            DataRow dataRow = dataTable.NewRow();
                            foreach (string current in dictionary.Keys)
                            {
                                dataRow[current] = dictionary[current];
                            }
                            dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
                        }
                    }
                }
                catch
                {
                }
                result = dataTable;
                return result;
            }
            #endregion

            #region 转换为string字符串类型
            /// <summary>
            ///  转换为string字符串类型
            /// </summary>
            /// <param name="s">获取需要转换的值</param>
            /// <param name="format">需要格式化的位数</param>
            /// <returns>返回一个新的字符串</returns>
            public static string ToStr(object s, string format)
            {
                string result = "";
                try
                {
                    if (format == "")
                    {
                        result = s.ToString();
                    }
                    else
                    {
                        result = string.Format("{0:" + format + "}", s);
                    }
                }
                catch
                {
                }
                return result;
            }
           #endregion
    }

}
